import sys, os, random
import cv
import math

from imagemanipulation import *

class Shuffler(object):
    def __init__(self, parent = None):
        self.parent = parent
    
    def shuffleImage(self, img_loc, cuts, im_width, im_height):
        
        cuts += 1
        img = cv.LoadImageM(img_loc)
        
        ## resize to be consistent
        thumbnail = cv.CreateMat(im_height, im_width, cv.CV_8UC3)
        cv.Resize(img,thumbnail)
        img = thumbnail
        
        ## compute top-left points where we want to take subrectangles from
        chunks = []
        for h in range(0, img.rows-img.rows/cuts+1, int(img.rows/cuts)):
            for v in range(0, img.cols-img.cols/cuts+1, int(img.cols/cuts)):
                chunks.append((v,h))
        
        ## extract subrectangles
        subimages = []
        for c in xrange(len(chunks)):
            sub = cv.CloneMat(cv.GetSubRect(img, (chunks[c][0],
                                      chunks[c][1],
                                      int(img.cols/cuts),
                                      int(img.rows/cuts))))
            subimages.append(sub)
        
        ## shuffle and get winning order
        orig = [i for i in subimages]
        random.shuffle(subimages)
        win_order = [orig.index(im) for im in subimages]
        
        return win_order, subimages